package com.starryx.driverschool.service.impl;

import com.starryx.driverschool.dao.UserRepository;
import com.starryx.driverschool.po.User;
import com.starryx.driverschool.service.UserService;
import com.starryx.driverschool.utils.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserServiecImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User checkUser(String username, String password, boolean flag) {
        User user = userRepository.findByUsernameAndPasswordAndFlag(username, password, flag);
        return user;
    }

    @Override
    public Page<User> listUser(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public User saveUser(User user) {
        user.setPassword(MD5Utils.code(user.getPassword()));
        user.setUpdateTime(new Date());
        return userRepository.save(user);
    }

    @Override
    public User getUser(Long id) {
        return userRepository.findOne(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    @Transactional
    @Override
    public User updateUser(Long id, User user) {
        User u = userRepository.findOne(id);
        if(u == null){
            throw new RuntimeException("不存在该类型");
        }
        BeanUtils.copyProperties(user, u);
        u.setPassword(MD5Utils.code(u.getPassword()));
        u.setUpdateTime(new Date());
        return userRepository.save(u);
    }

    @Transactional
    @Override
    public void deleteUser(Long id) {
        userRepository.delete(id);
    }
}
